package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-list-sys/cache"
	"novel-list-sys/modles"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var article []modles.Article
	redis_key := "article_list_page" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		modles.DB.Debug().Offset(offset).Limit(size).Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}

	var total int64
	modles.DB.Model(&article).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  article,
		"count": total,
	})
	return

}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var article modles.Article
	redis_key := "article_detail_id" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		modles.DB.Debug().Where("id =?", id).First(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": article,
	})
	return
}
